Using Conditional Statements with if, else, and switch in Swift
Course: iOS App Development Training
Topic: Using Conditional Statements with if, else, and switch
Course Link: iOS App Development Training at JustAcademy
Demo Link: Register for a Course Demo
Official Website: JustAcademy
1. Introduction to Conditional Statements in Swift
Conditional statements allow a program to make decisions based on whether a condition is true or false. Instead of executing every instruction in the same order, a program can select different actions depending on input, application state, or calculated results.
In iOS app development, conditional statements are used to validate forms, check login status, display messages, handle user permissions, determine prices, select application themes, and respond to user interactions.
For example, a login screen may display the home screen when the user is authenticated and show an error message when the credentials are incorrect.
Swift provides several ways to implement decision-making logic:
if — executes code when a condition is true.
if-else — selects between two alternatives.
else if — checks multiple conditions in sequence.
switch — selects a matching case from several alternatives.
- Nested conditions — place one conditional statement inside another when necessary.
2. Learning Objectives
After studying this topic, learners should be able to:
- Understand decision-making and Boolean conditions in Swift.
- Write conditional statements using
if and else.
- Use
else if to evaluate multiple conditions.
- Apply comparison and logical operators in conditions.
- Use
switch statements with values, ranges, and enumerations.
- Understand Swift's case matching and the role of
default.
- Combine conditions to implement practical application logic.
- Identify common conditional-statement errors.
- Build small decision-based programs for iOS applications.
3. Understanding Boolean Conditions
A condition is an expression that evaluates to a Boolean value: true or false. Swift requires the condition of an if statement to be a Boolean expression.
let age = 20
let isEligible = age >= 18
print(isEligible)
Output:
true
The expression age >= 18 checks whether the age is at least 18. Because the value is 20, the result is true.
Common Comparison Operators
| Operator |
Meaning |
Example |
== |
Equal to |
age == 18 |
!= |
Not equal to |
status != "Blocked" |
> |
Greater than |
score > 50 |
< |
Less than |
temperature < 10 |
>= |
Greater than or equal to |
marks >= 35 |
<= |
Less than or equal to |
items <= 5 |
Use == to compare two values for equality. A single = is the assignment operator and is not used as an equality condition.
4. Using the if Statement
The if statement executes a block of code only when its condition evaluates to true. If the condition is false, the block is skipped.
Syntax
if condition {
// Code runs when the condition is true.
}
Example: Checking a Passing Score
let marks = 78
if marks >= 35 {
print("You passed the examination.")
}
Output:
You passed the examination.
Because the marks are greater than or equal to 35, Swift executes the statements inside the if block.
Example: Checking Internet Connectivity
let isConnectedToInternet = true
if isConnectedToInternet {
print("You can load online content.")
}
This pattern can represent a simple connectivity decision. In a real iOS app, the application should use an appropriate networking or connectivity mechanism rather than assume connectivity from a fixed value.
Important Points
- The condition must evaluate to
true or false.
- Curly braces define the block of code controlled by the condition.
- If the condition is false and no alternative branch exists, the block is skipped.
- Indentation is not required for execution, but consistent indentation improves readability.
5. Using if-else Statements
An if-else statement provides two alternative execution paths. Swift executes the if block when the condition is true and the else block when it is false.
Syntax
if condition {
// Runs when the condition is true.
} else {
// Runs when the condition is false.
}
Example: Pass or Fail
let marks = 28
if marks >= 35 {
print("Result: Pass")
} else {
print("Result: Fail")
}
Output:
Result: Fail
Since the marks are below 35, the else block executes.
Example: Login Status
let isLoggedIn = false
if isLoggedIn {
print("Welcome to your account.")
} else {
print("Please log in to continue.")
}
Output:
Please log in to continue.
This is a common pattern for deciding which message to display. Real authentication should rely on the app's authentication flow and must not be implemented using a hard-coded Boolean alone.
6. Using else if for Multiple Conditions
The else if statement allows a program to check several conditions in sequence. Swift evaluates the conditions from top to bottom and executes the first matching branch. The remaining branches are skipped.
Syntax
if firstCondition {
// First branch.
} else if secondCondition {
// Second branch.
} else if thirdCondition {
// Third branch.
} else {
// Fallback branch.
}
Example: Assigning Grades
let marks = 86
if marks >= 90 {
print("Grade: A")
} else if marks >= 80 {
print("Grade: B")
} else if marks >= 70 {
print("Grade: C")
} else if marks >= 35 {
print("Grade: D")
} else {
print("Grade: F")
}
Output:
Grade: B
The first condition is false because 86 is less than 90. The second condition is true because 86 is at least 80, so Swift prints Grade B and skips the remaining branches.
Why Condition Order Matters
Place more restrictive or higher-priority conditions before broader conditions when the logic requires it.
let marks = 95
if marks >= 35 {
print("Pass")
} else if marks >= 90 {
print("Excellent")
} else {
print("Fail")
}
This example prints Pass, not Excellent, because the first condition is already true. The second condition can never be reached for marks of 90 or more. A corrected ordering is:
let correctedMarks = 95
if correctedMarks >= 90 {
print("Excellent")
} else if correctedMarks >= 35 {
print("Pass")
} else {
print("Fail")
}
7. Using Logical Operators in Conditions
Logical operators combine or reverse Boolean expressions. They help implement decisions that depend on more than one requirement.
| Operator |
Name |
Meaning |
&& |
Logical AND |
True only when both conditions are true. |
|| |
Logical OR |
True when at least one condition is true. |
! |
Logical NOT |
Reverses a Boolean value. |
7.1 Logical AND
let age = 24
let hasValidID = true
if age >= 18 && hasValidID {
print("Requirements satisfied.")
} else {
print("Requirements not satisfied.")
}
Both conditions must be true for the first branch to execute.
7.2 Logical OR
let isPremiumUser = false
let hasPromoCode = true
if isPremiumUser || hasPromoCode {
print("Discount available.")
} else {
print("No discount available.")
}
The first branch executes because at least one condition is true.
7.3 Logical NOT
let isAccountLocked = false
if !isAccountLocked {
print("Account is not locked.")
}
The ! operator reverses the Boolean value. Here, !isAccountLocked evaluates to true.
8. Nested if Statements
A nested if statement is a conditional statement placed inside another conditional block. It is useful when one decision should only be evaluated after another requirement has been satisfied.
let isLoggedIn = true
let hasCompletedProfile = false
if isLoggedIn {
if hasCompletedProfile {
print("Open the dashboard.")
} else {
print("Please complete your profile.")
}
} else {
print("Please log in first.")
}
Output:
Please complete your profile.
The inner condition is checked only when the outer condition is true. Although nesting is useful, too many levels can make code difficult to read. Consider combining conditions or extracting logic into functions when appropriate.
9. Using switch Statements in Swift
A switch statement selects a code block by matching a value against one or more cases. It is often clearer than a long if-else if chain when comparing a single value against several possible alternatives.
Syntax
switch value {
case patternOne:
// Code for the first matching case.
case patternTwo:
// Code for the second matching case.
default:
// Fallback code when no case matches.
}
Example: Selecting a Menu Option
let menuOption = 2
switch menuOption {
case 1:
print("Open Profile")
case 2:
print("Open Settings")
case 3:
print("Open Help")
default:
print("Invalid menu option")
}
Output:
Open Settings
Swift checks the cases and executes the matching branch. In this example, the value 2 matches the second case.
Swift switch Does Not Implicitly Fall Through
Unlike switch statements in some other languages, Swift does not automatically continue executing the next case after a matched case finishes. Each case normally ends its execution automatically. If shared execution is needed, use a suitable structure such as a combined case or call a shared function.
10. The default Case
The default case handles values that do not match any explicitly listed case. Swift generally requires a switch over a non-exhaustive set of possible values to cover every possibility, often using default.
let dayNumber = 9
switch dayNumber {
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
default:
print("Invalid day number")
}
Output:
Invalid day number
The value 9 does not match any listed day, so the default branch runs.
11. Matching Multiple Values in a switch Case
Swift allows a case to match multiple values by separating them with commas. This helps avoid repeating the same code for several related alternatives.
let day = "Saturday"
switch day {
case "Saturday", "Sunday":
print("It's the weekend.")
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
print("It's a weekday.")
default:
print("Unknown day.")
}
Output:
It's the weekend.
This technique is useful for grouping related menu choices, status codes, categories, or days of the week.
12. Using Ranges in switch Statements
Swift supports range patterns in switch statements. They are useful when a value must be classified into numerical intervals.
let score = 82
switch score {
case 90...100:
print("Excellent")
case 75..<90:
print("Very Good")
case 50..<75:
print("Good")
case 35..<50:
print("Needs Improvement")
case 0..<35:
print("Fail")
default:
print("Invalid score")
}
Output:
Very Good
The range 90...100 includes both endpoints. The range 75..<90 includes 75 but excludes 90. The default case also handles values outside the expected score range.
13. Using switch with Enumerations
Enumerations, or enums, define a type with a finite set of related values. A switch statement is especially useful for handling each possible enum case clearly.
enum AppScreen {
case home
case profile
case settings
case help
}
let selectedScreen = AppScreen.settings
switch selectedScreen {
case .home:
print("Display Home Screen")
case .profile:
print("Display Profile Screen")
case .settings:
print("Display Settings Screen")
case .help:
print("Display Help Screen")
}
Output:
Display Settings Screen
Because the switch covers every case of this enumeration, it does not need a default branch. Exhaustive switches are valuable because the compiler can report when a newly added enum case has not been handled.
14. Using where in a switch Case
The where keyword adds an extra condition to a case. It is helpful when a pattern matches a value but the program also needs to check an additional requirement.
let score = 88
switch score {
case 0..<100 where score >= 85:
print("High score")
case 0..<100:
print("Regular score")
default:
print("Invalid score")
}
Output:
High score
The first case matches scores in the range 0 to 99 and additionally requires the score to be at least 85. Values in the same range that fail the extra condition can match the next range case.
15. Comparing if-else and switch
| Feature |
if-else |
switch |
| Primary use |
Evaluate Boolean conditions. |
Match a value against patterns or alternatives. |
| Multiple conditions |
Uses else if branches. |
Uses multiple case branches. |
| Ranges |
Can use comparison operators. |
Can use range patterns. |
| Enums |
Can compare enum values in conditions. |
Often provides clear, exhaustive handling of enum cases. |
| Fallback |
else |
default, when needed |
| Best use |
Conditions involving different expressions or complex Boolean logic. |
Several alternatives for a value or pattern. |
16. Conditional Statements in SwiftUI
SwiftUI uses Swift conditional logic to decide what content a view displays. Conditional view construction allows interfaces to respond to state, user actions, and application data.
Example: Showing Login or Welcome Text
import SwiftUI
struct LoginStatusView: View {
let isLoggedIn = true
var body: some View {
VStack {
if isLoggedIn {
Text("Welcome back!")
.font(.title)
} else {
Text("Please log in.")
.font(.title)
}
}
.padding()
}
}
The view displays one text element based on the value of isLoggedIn. Since the value is a constant in this example, the displayed branch does not change during the view's lifetime unless the view is recreated with different data.
Example: Interactive Conditional UI
import SwiftUI
struct AvailabilityView: View {
@State private var isAvailable = false
var body: some View {
VStack(spacing: 12) {
if isAvailable {
Text("The service is available.")
.foregroundStyle(.green)
} else {
Text("The service is currently unavailable.")
.foregroundStyle(.red)
}
Button("Change Status") {
isAvailable.toggle()
}
}
.padding()
}
}
The @State property stores a changing Boolean value. When the button toggles the state, SwiftUI reevaluates the view and displays the corresponding conditional branch.
17. Common Mistakes and Troubleshooting
| Mistake |
Why It Is Wrong |
How to Fix It |
Using = instead of == |
= assigns a value rather than comparing equality. |
Use == for equality checks. |
| Using an integer as a condition |
Swift requires a Boolean condition. |
Write an explicit comparison, such as count > 0. |
| Incorrect condition order |
A broad condition can match before a more specific one. |
Put higher-priority conditions first. |
| Forgetting braces |
Swift conditional blocks require braces. |
Wrap the statements in { }. |
| Missing a switch case |
A switch over an enum or other non-exhaustive possibilities may fail to compile. |
Handle every possible case or use default when appropriate. |
| Expecting automatic switch fallthrough |
Swift ends a matched case without implicitly executing the next one. |
Combine cases or explicitly structure shared behavior. |
| Overusing nested conditions |
Deep nesting makes logic harder to read. |
Use guard clauses, combined conditions, or helper functions where appropriate. |
| Ignoring boundary values |
Values at the edge of a range may be classified incorrectly. |
Test minimum, maximum, and boundary values. |
Example: Correcting a Non-Boolean Condition
Incorrect:
let age = 21
// Invalid Swift:
// if age {
// print("Eligible")
// }
Correct:
let age = 21
if age >= 18 {
print("Eligible")
}
18. Best Practices for Conditional Logic
- Keep each condition clear and easy to understand.
- Use
if-else for Boolean decisions and switch for matching multiple alternatives.
- Order
else if branches carefully.
- Use meaningful names for Boolean variables, such as
isEnabled or hasPermission.
- Handle unexpected input and invalid ranges explicitly.
- Prefer exhaustive switches for enumerations when possible.
- Avoid unnecessary nested conditions.
- Test both true and false outcomes.
- Test boundary values for numerical conditions.
- Keep security-sensitive decisions on trusted systems when required; a client-side condition alone is not an authorization mechanism.
19. Practical Exercises
Exercise 1: Age Eligibility
Create an integer constant named age. Use an if-else statement to print whether the person meets an age requirement of 18.
Exercise 2: Positive, Negative, or Zero
Use if, else if, and else to determine whether an integer is positive, negative, or zero.
Exercise 3: Grade Calculator
Use an else if chain to assign grades according to marks. Ensure that the conditions are ordered correctly and invalid scores are handled.
Exercise 4: Day of the Week
Use a switch statement to map values from 1 through 7 to day names. Display a message for invalid values.
Exercise 5: Subscription Status
Create an enumeration with cases such as free, premium, and expired. Use a switch statement to display the appropriate message for each case.
Exercise 6: Shopping Discount
Check a shopping total and whether the customer has a valid coupon. Use logical operators to determine whether a discount should be applied.
20. Mini Project: iOS Order Status Checker
Project objective: Create a small Swift program that displays an appropriate message for an order's current status using an enumeration and a switch statement.
Project Code
enum OrderStatus {
case placed
case confirmed
case shipped
case delivered
case cancelled
}
let currentStatus = OrderStatus.shipped
switch currentStatus {
case .placed:
print("Your order has been placed.")
case .confirmed:
print("Your order has been confirmed.")
case .shipped:
print("Your order is on the way.")
case .delivered:
print("Your order has been delivered.")
case .cancelled:
print("Your order has been cancelled.")
}
Project Explanation
OrderStatus defines the possible states of an order.
currentStatus stores the current state as an enum value.
- The
switch statement selects the message corresponding to the state.
- Each case represents a distinct order status.
- Because every enum case is handled, the switch is exhaustive without a
default case.
Extension task: Create a SwiftUI screen that displays the order status and uses buttons to change between statuses. Use an appropriate state-management mechanism so the interface updates when the status changes.
21. Interview Questions and Answers
Q1. What is a conditional statement in Swift?
Answer: A conditional statement controls program execution based on a condition. It allows an application to perform different actions depending on whether a condition is true or false.
Q2. What is the difference between if and if-else?
Answer: An if statement executes code only when its condition is true. An if-else statement provides two branches, allowing one block to execute when the condition is true and another when it is false.
Q3. When should you use else if?
Answer: Use else if when multiple conditions must be checked in sequence, such as assigning grades based on examination marks.
Q4. What is a switch statement?
Answer: A switch statement compares a value against multiple patterns and executes the first matching case. It supports individual values, multiple-value cases, ranges, and enumeration cases.
Q5. Is the default case always required in Swift?
Answer: No. A switch must be exhaustive, but a default case is unnecessary when all possible values are already covered, such as when every case of an enumeration is handled.
Q6. Does Swift require break after every switch case?
Answer: No. Swift does not implicitly fall through to the next case, so an ordinary break is not required at the end of each case.
Q7. Can a switch statement handle ranges?
Answer: Yes. Swift supports range patterns such as case 1...10 and case 11..<20.
Q8. What is the difference between && and ||?
Answer: The && operator requires both conditions to be true, while || requires at least one condition to be true.
Q9. Can conditional statements be used in SwiftUI?
Answer: Yes. SwiftUI views can use if and other conditional logic to display different interface elements based on application state.
Q10. What is a nested if statement?
Answer: A nested if statement is an if statement placed inside another conditional block. It is useful when one decision depends on another decision.
Q11. Why is condition ordering important?
Answer: Swift executes the first matching branch in an if-else if chain. If a broad condition appears first, it may prevent a more specific condition from being evaluated.
Q12. What is the purpose of where in a switch statement?
Answer: The where clause adds an extra Boolean condition that must be satisfied for a case to match.
22. Quick Revision Checklist
if executes a block when a Boolean condition is true.
else handles the alternative path.
else if checks additional conditions in sequence.
switch matches a value against patterns.
default covers unmatched possibilities when needed.
&& means logical AND.
|| means logical OR.
! reverses a Boolean value.
- Swift conditions must evaluate to Boolean values.
- Switch statements must be exhaustive.
- Swift switch cases do not fall through automatically.
- Ranges and enumerations can simplify complex decision logic.
- Test boundary conditions and unexpected values.
23. Conclusion
Conditional statements are essential for building responsive and intelligent iOS applications. Swift's if, else, and else if statements handle Boolean decisions, while switch provides a structured approach to matching values, ranges, and enumeration cases.
By practising these techniques, developers can implement validation, navigation decisions, order-status messages, login flows, grading systems, and dynamic SwiftUI interfaces. Writing clear conditions, ordering branches carefully, and handling every relevant case will make Swift applications more reliable and easier to maintain.
24. Additional Learning Resources